package com.shop.controller;

import com.shop.pojo.Employee;
import com.shop.service.EmployeeService;
import com.shop.utils.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @RequestMapping(value = "/login")
    public String login(String username, String password, HttpSession session, Model model) {

        Employee employee = this.employeeService.checkLogin(username);

        if (username != null) {
            if (employee.getPassword().equals(password)) {
            // 用户名 & 密码 都正确
                // session 存入 employee
                session.setAttribute(Constants.GLOBLE_USER_SESSION, employee);

                return "index";

            } else {
                model.addAttribute("errorMsg", "帐号/密码不正确");
                return "login";
            }
        } else {
            // 账户 or 密码 不正确
            model.addAttribute("errorMsg", "帐号/密码不正确");
            return "login";
        }

        // End
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) {

        // session.失效()
        session.invalidate();

        // 重定向到 login.jsp
        return "redirect:/login.jsp";
    }

}
